using UnityEngine;
using System.Collections;

public class BulletTrail : MonoBehaviour
{
    [Header("轨迹设置")]
    public float trailDuration = 0.3f;
    public float trailWidth = 0.01f;
    public Gradient trailColor = new Gradient();
    public AnimationCurve widthCurve = AnimationCurve.Linear(0, 1, 1, 0);
    
    [Header("使用Line Renderer")]
    public bool useLineRenderer = true;
    
    private LineRenderer lineRenderer;
    private ParticleSystem particleSystemInfo;
    private ParticleSystem.ShapeModule particleShape;
    private bool isInitialized = false;
    private float startTime;
    private bool isActive = false;
    private Vector3 startPosition;
    private Vector3 endPosition;
    
    void Awake()
    {
        InitializeTrail();
    }
    
    void InitializeTrail()
    {
        if (isInitialized) return;
        
        if (useLineRenderer)
        {
            SetupLineRenderer();
        }
        else
        {
            SetupParticleSystem();
        }
        
        // 初始化颜色渐变
        if (trailColor == null || trailColor.alphaKeys.Length == 0)
        {
            trailColor = CreateDefaultGradient();
        }
        
        isInitialized = true;
    }
    
    void SetupLineRenderer()
    {
        lineRenderer = GetComponent<LineRenderer>();
        if (lineRenderer == null)
            lineRenderer = gameObject.AddComponent<LineRenderer>();
        
        lineRenderer.positionCount = 2;
        lineRenderer.widthMultiplier = trailWidth;
        lineRenderer.colorGradient = trailColor;
        lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
        lineRenderer.widthCurve = widthCurve;
        lineRenderer.useWorldSpace = true;
        lineRenderer.receiveShadows = false;
        lineRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        
        // 初始隐藏
        lineRenderer.enabled = false;
    }
    
    void SetupParticleSystem()
    {
        particleSystemInfo = GetComponent<ParticleSystem>();
        if (particleSystemInfo == null)
            particleSystemInfo = gameObject.AddComponent<ParticleSystem>();
        
        var main = particleSystemInfo.main;
        main.duration = trailDuration;
        main.startLifetime = trailDuration;
        main.startSpeed = 0;
        main.startSize = trailWidth;
        main.startColor = trailColor;
        main.loop = false;
        main.playOnAwake = false;
        main.maxParticles = 1;
        
        var emission = particleSystemInfo.emission;
        emission.rateOverTime = 0;
        emission.enabled = false;
        
        // 正确获取Shape模块的引用
        particleShape = particleSystemInfo.shape;
        particleShape.shapeType = ParticleSystemShapeType.SingleSidedEdge;
        particleShape.radius = 0.01f;
        particleShape.enabled = true;
        
        var renderer = GetComponent<ParticleSystemRenderer>();
        if (renderer.material == null)
        {
            renderer.material = new Material(Shader.Find("Particles/Standard Unlit"));
        }
        
        // 初始停止粒子系统
        particleSystemInfo.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
    }
    
    Gradient CreateDefaultGradient()
    {
        Gradient gradient = new Gradient();
        gradient.colorKeys = new GradientColorKey[] 
        {
            new GradientColorKey(Color.yellow, 0f),
            new GradientColorKey(Color.red, 1f)
        };
        gradient.alphaKeys = new GradientAlphaKey[] 
        {
            new GradientAlphaKey(1f, 0f),
            new GradientAlphaKey(0f, 1f)
        };
        return gradient;
    }
    
    void Update()
    {
        if (isActive)
        {
            UpdateTrail();
        }
    }
    
    void UpdateTrail()
    {
        float elapsedTime = Time.time - startTime;
        float progress = elapsedTime / trailDuration;
        
        if (useLineRenderer)
        {
            UpdateLineRendererTrail(progress);
        }
        else
        {
            UpdateParticleTrail(progress);
        }
        
        if (elapsedTime >= trailDuration)
        {
            isActive = false;
            if (useLineRenderer)
                lineRenderer.enabled = false;
        }
    }
    
    void UpdateLineRendererTrail(float progress)
    {
        // 更新宽度
        lineRenderer.widthMultiplier = trailWidth * widthCurve.Evaluate(progress);
        
        // 更新颜色透明度
        Gradient gradient = lineRenderer.colorGradient;
        GradientAlphaKey[] alphaKeys = gradient.alphaKeys;
        for (int i = 0; i < alphaKeys.Length; i++)
        {
            alphaKeys[i].alpha = Mathf.Lerp(alphaKeys[i].alpha, 0, progress);
        }
        gradient.alphaKeys = alphaKeys;
        lineRenderer.colorGradient = gradient;
    }
    
    void UpdateParticleTrail(float progress)
    {
        // 粒子系统会自动处理消失
    }
    
    /// <summary>
    /// 创建子弹轨迹
    /// </summary>
    /// <param name="startPos">起始位置</param>
    /// <param name="endPos">结束位置</param>
    public void CreateTrail(Vector3 startPos, Vector3 endPos)
    {
        if (!isInitialized)
        {
            InitializeTrail();
        }
        
        startPosition = startPos;
        endPosition = endPos;
        startTime = Time.time;
        isActive = true;
        
        if (useLineRenderer)
        {
            CreateLineRendererTrail(startPos, endPos);
        }
        else
        {
            CreateParticleTrail(startPos, endPos);
        }
    }
    
    void CreateLineRendererTrail(Vector3 startPos, Vector3 endPos)
    {
        if (lineRenderer == null)
        {
            SetupLineRenderer();
        }
        
        lineRenderer.SetPosition(0, startPos);
        lineRenderer.SetPosition(1, endPos);
        lineRenderer.enabled = true;
        
        // 重置颜色
        lineRenderer.colorGradient = trailColor;
        lineRenderer.widthMultiplier = trailWidth;
    }
    
    void CreateParticleTrail(Vector3 startPos, Vector3 endPos)
    {
        if (particleSystemInfo == null || !particleShape.enabled)
        {
            Debug.LogError("粒子系统未正确初始化");
            return;
        }
        
        // 计算方向和距离
        Vector3 direction = (endPos - startPos).normalized;
        float distance = Vector3.Distance(startPos, endPos);
        
        try
        {
            // 设置粒子系统形状 - 确保使用正确的模块引用
            particleShape.radius = distance;
            
            // 定位和旋转粒子系统
            transform.position = startPos;
            transform.rotation = Quaternion.LookRotation(direction);
            
            // 发射粒子
            particleSystemInfo.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
            particleSystemInfo.Play();
        }
        catch (System.Exception e)
        {
            Debug.LogError($"创建粒子轨迹失败: {e.Message}");
            // 回退到Line Renderer
            useLineRenderer = true;
            SetupLineRenderer();
            CreateLineRendererTrail(startPos, endPos);
        }
    }
    
    /// <summary>
    /// 立即隐藏轨迹
    /// </summary>
    public void HideTrail()
    {
        isActive = false;
        if (useLineRenderer && lineRenderer != null)
        {
            lineRenderer.enabled = false;
        }
        if (particleSystemInfo != null)
        {
            particleSystemInfo.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
        }
    }
    
    /// <summary>
    /// 设置轨迹颜色
    /// </summary>
    public void SetTrailColor(Gradient newColor)
    {
        trailColor = newColor;
        if (useLineRenderer && lineRenderer != null)
        {
            lineRenderer.colorGradient = trailColor;
        }
    }
    
    /// <summary>
    /// 设置轨迹宽度
    /// </summary>
    public void SetTrailWidth(float width)
    {
        trailWidth = width;
        if (useLineRenderer && lineRenderer != null)
        {
            lineRenderer.widthMultiplier = trailWidth;
        }
    }
    
    /// <summary>
    /// 安全初始化方法，可在运行时调用
    /// </summary>
    public void SafeInitialize()
    {
        if (!isInitialized)
        {
            InitializeTrail();
        }
    }
}